﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using SmartVault.Proto;
using CSharpTest.Net.Crypto;
using SmartVault.Core;
using SmartVault.Net.Http;
using SmartVault.Net;
using SmartVault.OAuth.Autonomous;

namespace SmartVault.Rest
{
    /// <summary>
    /// Authentication
    /// 
    /// This class is used to performed the basic steps of authentication. 
    /// The authentication steps MUST always be performed server side to protect
    /// the trust relationship between SmartVault and your webserver. 
    /// 
    /// Delegated Operations (those you perform as a user *may* be performed at 
    /// the client by passing the access token back to your client). 
    /// </summary>
    public class Authentication
    {
        private ServerCfg ServerCfg { get; set; }
        private Uri RootUri { get { return this.ServerCfg.RootUri;  } }
        private MediaType MediaType { get { return this.ServerCfg.MediaType;  } }
        private Encoding Encoding { get { return this.ServerCfg.Encoding;  } }
        private string ClientId { get { return this.ServerCfg.ClientId;  } }
        private RSAPrivateKey2 PrivateKey { get { return this.ServerCfg.PrivateKey; } }

        private NetWebClient Client
        {
            get { return new NetWebClient(new WebRequestInfo(this.RootUri, null, null, this.MediaType, this.Encoding)); }   
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="cfg"></param>
        public Authentication(ServerCfg cfg)
        {
            this.ServerCfg = cfg;
        }

        /// <summary>
        /// GetClientAccessToken
        /// 
        /// Get a client access token.
        /// </summary>
        /// <returns></returns>
        public ClientCfg GetClientAccessToken()
        {
            AbsolutePath pth = new AbsolutePath(Constants.NoncePath);

            // retrieve the nonce
            ClientNetContext ctx = Client.Open(pth.ToString(), HttpMethods.POST.ToString(), null);
            NonceRequest.Builder nb = NonceRequest.CreateBuilder();
            nb.ClientId = this.ClientId;
            ctx.WritePayload(nb.Build());
            NonceResponse n = ctx.ReadPayload<NonceResponse>();
            //serializer.Write(ProtoFormats.XML, Console.Out, n);
            SelfTokenEncoder ste = new SelfTokenEncoder(this.ClientId, n.Message.Code);

            ClientTokenRequest.Builder bld = ClientTokenRequest.CreateBuilder();
            bld.Token = ste.Generate(this.PrivateKey);

            ctx = Client.Open(Constants.ClientTokenPath, HttpMethods.POST.ToString(), null);
            ctx.WritePayload(bld.Build());
            ClientTokenResponse token = ctx.ReadPayload<ClientTokenResponse>();

            return new ClientCfg(this.ClientId, token.Message.Token, ServerCfg);
        }

        /// <summary>
        /// CreateClientProtocol
        /// 
        /// Create an object that can be used to perform operations as the client. This is 
        /// for server to server operations.
        /// </summary>
        /// <returns></returns>
        public ClientProtocol CreateClientProtocol()
        {
            return new ClientProtocol(GetClientAccessToken());
        }
    }
}
